<template>
  <el-dialog
    :model-value="modelValue"
    :title="dialogTitle"
    width="40%"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="分类图标" prop="icon">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers="uploadHeaders"
          name="file"
          :show-file-list="false"
          :on-success="handleIconSuccess"
          :on-error="(err) => ElMessage.error('上传失败: ' + err)"
          :before-upload="beforeIconUpload"
        >
          <img v-if="form.icon" :src="form.icon" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <el-form-item label="排序号" prop="sort">
        <el-input-number v-model="form.sort" :min="0" />
      </el-form-item>

      <el-form-item label="父级分类" prop="parentId">
        <el-select v-model="form.parentId" placeholder="请选择父级分类">
          <el-option :value="0" label="顶级分类" />
          <el-option
            v-for="item in parentOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="层级" prop="level">
        <el-select v-model="form.level" placeholder="请选择层级">
          <el-option
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, defineProps, watch, onMounted } from "vue";
import {
  createCategory,
  updateCategory,
  getTopCategories,
} from "@/api/category";
import { ElMessage } from "element-plus";
import { rules, defaultForm, levelOptions } from "../options";
import { Plus } from "@element-plus/icons-vue";

// 获取token
const getToken = () => {
  return localStorage.getItem("token") || "";
};

// 上传URL
const uploadUrl = `${import.meta.env.VITE_UPLOADS_URL}/api/FileUploadManage/upload`;

// 上传请求头
const uploadHeaders = {
  Authorization: `Bearer ${getToken()}`,
};

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  dialogTitle: {
    type: String,
    default: "",
    required: true,
  },
  dialogTableValue: {
    type: Object,
    default: () => ({}),
  },
});

const formRef = ref(null);
const form = ref({ ...defaultForm });
const parentOptions = ref([]);

// 获取父级分类选项
onMounted(async () => {
  const res = await getTopCategories();
  parentOptions.value = res.data.data;
});

// 监听表单数据变化
watch(
  () => props.dialogTableValue,
  (newVal) => {
    if (newVal) {
      form.value = { ...defaultForm, ...newVal };
    }
  },
  { deep: true, immediate: true }
);

const emits = defineEmits(["update:modelValue", "initGetList"]);

const handleClose = () => {
  emits("update:modelValue", false);
};

// 图标上传成功处理
const handleIconSuccess = (response) => {
  if (response.result) {
    form.value.icon = `${import.meta.env.VITE_UPLOADS_URL}${response.filePath}`;
    ElMessage.success(response.message || "上传成功");
  } else {
    ElMessage.error("上传失败: " + (response.message || "未知错误"));
  }
};

// 图标上传前验证
const beforeIconUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg";
  const isPNG = rawFile.type === "image/png";
  const isSVG = rawFile.type === "image/svg+xml";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG && !isSVG) {
    ElMessage.error("图标必须是 JPG/PNG/SVG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图标大小不能超过2MB!");
    return false;
  }
  return true;
};

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (props.dialogTitle === "添加分类") {
          await createCategory(form.value);
        } else {
          await updateCategory(form.value);
        }

        ElMessage({
          message: props.dialogTitle === "添加分类" ? "添加成功" : "更新成功",
          type: "success",
        });

        emits("initGetList");
        handleClose();
      } catch (error) {
        console.error("操作失败:", error);
      }
    } else {
      console.log("表单验证失败");
      return false;
    }
  });
};
</script>

<style>
.dialog-footer {
  padding: 20px 0 0;
  text-align: right;
}

/* 上传组件样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>
